package fei.zhou.gatewaydemo.filter;

import java.util.Arrays;
import java.util.List;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

@Component
public class MyParam11GatewayFilterFactory extends AbstractGatewayFilterFactory<MyParam11GatewayFilterFactory.Config> {
    
    static final String PARAM_NAME = "param";
    
    public MyParam11GatewayFilterFactory() {
        super(Config.class);
    }
    
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }
    
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // http://localhost:10010/user/8?name=userId config.param ==> name
            // 获取请求参数中param对应的参数名 的参数值
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.param)) {
                request.getQueryParams().get(config.param).forEach(
                        value -> System.out.println("------------局部过滤器-------参数名字:" + config.param + "--参数值:" + value));
            }
            return chain.filter(exchange);
        };
    }
    
    public static class Config {
        // 对应在配置过滤器的时候指定的参数名
        private String param;
        
        public String getParam() {
            return param;
        }
        
        public void setParam(String param) {
            this.param = param;
        }
    }
}
